package com.hsq.ndmall.product.service.impl;

import com.google.common.collect.Maps;
import com.hsq.ndmall.product.entity.GoodsProductEntity;
import com.hsq.ndmall.product.service.GoodsProductService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hsq.ndmall.product.dao.CommentDao;
import com.hsq.ndmall.product.entity.CommentEntity;
import com.hsq.ndmall.product.service.CommentService;
import com.hsq.ndmall.common.utils.PageUtils;
import com.hsq.ndmall.common.utils.Query;

@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {

    @Autowired
    GoodsProductService goodsProductService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CommentEntity> page = this.page(
                new Query<CommentEntity>().getPage(params),
                getQueryWrapper(params)
        );

        return new PageUtils(page);
    }

    private QueryWrapper getQueryWrapper(Map<String, Object> params) {
//        QueryWrapper<CommentEntity> queryWrapper = new QueryWrapper<>();
//        if (params.containsKey("goods_id")) {
//            List<GoodsProductEntity> goodsProduct = goodsProductService.list(new QueryWrapper<GoodsProductEntity>().lambda().eq(GoodsProductEntity::getGoodsId,params.get("goods_id")));
//            for (GoodsProductEntity goodsProductEntity : goodsProduct) {
//                queryWrapper.lambda().eq(CommentEntity::getProductId,goodsProductEntity.getId());
//            }
//        }
//        return queryWrapper;
        QueryWrapper<CommentEntity> goodsEntityQueryWrapper = new QueryWrapper<>();
        if (params.containsKey("goods_id")) {
            //查询该商品的所有货品ID
            Map paraMap = Maps.newHashMap();
            paraMap.put("goods_id", params.get("goods_id"));
            PageUtils pageUtils = goodsProductService.queryPage(paraMap);
            List productIds = new ArrayList<Integer>();
            pageUtils.getList().forEach(e -> {
                if (e instanceof GoodsProductEntity) {
                    GoodsProductEntity goodsProductEntity = (GoodsProductEntity) e;
                    productIds.add(goodsProductEntity.getId());
                }
            });

            //查询所有获评的评论
            goodsEntityQueryWrapper.lambda().in(CommentEntity::getProductId,productIds);
        }
        //查询的商品必须是逻辑上未删除的商品
        //goodsEntityQueryWrapper.lambda().eq(CommentEntity::, 0);
        return goodsEntityQueryWrapper;
    }
}
